import { h, onMounted, reactive, ref, toRaw } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps } from "../utils/types";
import { addDialog } from "@/components/ReDialog";
import { deviceDetection } from "@pureadmin/utils";
import editForm from "../form.vue";
import { message } from "@/utils/message";
import Details from "../detail.vue";
import {
  getDeliveryOrderListApi,
  createDeliveryOrderApi,
  updateDeliveryOrderApi,
  delDeliveryOrderApi,
  getDeliveryOrderShowApi
} from "@/api/deliveryOrderApi";
import {
	getMaterialListApi
} from "@/api/materialApi";
export function usePage() {
  const form = reactive({
    page: 1,
    perPage: 10,
    orderNo: null
  });
  const formRef = ref();
  const dataList = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const getOrderType = (type) => {
    switch (type) {
      case 1:
        return "销售出库";
      case 2:
        return "生产领料";
	  case 3:
	    return "其他出库";
	  case 4:
	    return "采购退货";
    }
  };
  const getStatusType = (type) => {
    switch (type) {
      case 1:
        return "待执行";
      case 2:
        return "已执行";
  	  case 3:
  	    return "待执行，出库";
  	  case 4:
  	    return "已执行，出库";
  	  case 5:
  	    return "其他";
    }
  };
  
  const columns: TableColumnList = [
    {
      label: "ID",
      prop: "deliveryOrderId",
      width: 80
    },
	{
	  label: "出库单号",
	  prop: "orderNo",
	  minWidth: 130
	},
    {
      label: "单据类型",
      prop: "orderType",
      minWidth: 130,
	  formatter: (row) => {
	  	return getOrderType(row.orderType)
	  }
    },
	{
	  label: "客户",
	  prop: "customer.name",
	  minWidth: 130
	},
	{
	  label: "单据状态",
	  prop: "status",
	  minWidth: 130,
	  formatter: (row) => {
	  	return getStatusType(row.status)
	  }
	},
    {
    	label: "创建者",
    	prop: "createUser.username",
    	minWidth: 100
    },
    {
    	label: "创建时间",
    	prop: "createdAt",
    	minWidth: 160
    },
	{
		label: "备注",
		prop: "remarks",
		minWidth: 100
	},
	{
		label: "单据进度",
		prop: "createdAt",
		minWidth: 160,
		cellRenderer: ({ row }) => <div><el-progress percentage={0} /></div>
	},
    {
      label: "操作",
      fixed: "right",
      slot: "operation",
	  width: 180
    }
  ];
  function handleSizeChange(val: number) {
    loading.value = true;
    form.page = 1;
    form.perPage = val;
    getDeliveryOrderListApi(toRaw(form)).then(result => {
      dataList.value = result.result.list;
      pagination.total = result.result.total;
      pagination.pageSize = result.result.perPage*1;
      pagination.currentPage = 1;
    });

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  function handleCurrentChange(val: number) {
    loading.value = true;
    form.page = val;
	console.log(val)
    getDeliveryOrderListApi(toRaw(form)).then(result => {
      dataList.value = result.result.list;
      pagination.total = result.result.total;
	  pagination.pageSize = result.result.perPage*1;
	  pagination.currentPage = val;
    });

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  async function onSearch() {
    loading.value = true;
    const { result } = await getDeliveryOrderListApi(toRaw(form));
    dataList.value = result.list;
    pagination.total = result.total;
    pagination.pageSize = result.perPage*1;
    pagination.currentPage = result.page*1;

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }
  const materialOptions = ref()
  const getMaterialData = async() => {
  	const res = await getMaterialListApi({page:1, perPage: 9999})
  	if(res?.code === 200) {
  		materialOptions.value = res.result.list
  	}
  }
  const resetForm = formEl => {
    if (!formEl) return;
    form.orderNo = null;
    formEl.resetFields();
    onSearch();
  };
  const formInline = ref();
  async function openDialog(title = "新增", row?: FormItemProps) {
	
    if (`${title}` == "新增") {
      formInline.value = {
        title: "新增",
		orderNo: 'SH'+(new Date()).toLocaleString().replace(/[:/ ]/g, ''),
		materialOptions: materialOptions.value
      };
    } else {
      const res = await getDeliveryOrderShowApi({
        deliveryOrderId: row?.deliveryOrderId
      });
	  if(res.code !== 200) {
	  	message(res.msg ?? "操作失败,请联系管理员", {
	  	  type: "error"
	  	});
	  	return
	  }
      formInline.value = {
        title: "修改",
		materialOptions: materialOptions.value,
        deliveryOrderId: res?.result?.deliveryOrderId ?? null,
		orderNo: res?.result?.orderNo ?? null,
		orderType: res?.result?.orderType ?? null,
		materialList: res?.result?.orderProducts ?? [],
		productList: res?.result?.orderProducts ?? [],
		customerId: res?.result?.customerId ?? null,
		remarks: res?.result?.remarks ?? "",
		entityCode: res?.result?.entityCode ?? "",
      };
    }
    addDialog({
      title: `${title}出库单信息`,
      props: {
        formInline: formInline
      },
      width: "75%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了出库单`, {
            type: "success"
          });
          done();
          onSearch();
        }
		
        FormRef.validate(valid => {
          if (valid) {
			if(curData.productList.length === 0) {
				message("请添加物料", {
				  type: "error"
				});
				return
			}
			if(curData.productList.length > 0) {
				for (let item of curData.productList) {
					if(!item.materialId) {
						message("请选择物料", {
						  type: "error"
						});
						return
					}
					if(!item.planNum) {
						message("请输入计划数量", {
						  type: "error"
						});
						return
					}
					if(!item.realNum) {
						message("请输入实际数量", {
						  type: "error"
						});
						return
					}
					if(!item.batchNo) {
						message("请输入批次号", {
						  type: "error"
						});
						return
					}
					if(!item.produceDate) {
						message("请选择生产日期", {
						  type: "error"
						});
						return
					}
				}
			}
			let params = {
				orderNo: curData.orderNo,
				orderType: curData.orderType,
				customerId: curData.customerId,
				entityCode: curData.entityCode,
				remarks: curData.remarks,
				productList: curData.productList,
				deliveryOrderId: curData.deliveryOrderId,
			}
            if (title === "新增") {
              createDeliveryOrderApi(params)
                .then((res) => {
				  if(res.code !== 200) {
				  	message(res.msg ?? "操作失败,请联系管理员", {
				  	  type: "error"
				  	});
				  	return
				  }
                  chores();
                })
                .catch(error => {
                  message(error.response.data.msg ?? "操作失败,请联系管理员", {
                    type: "error"
                  });
                });
            } else {
              updateDeliveryOrderApi(params)
                .then((res) => {
				  if(res.code !== 200) {
				  	message(res.msg ?? "操作失败,请联系管理员", {
				  	  type: "error"
				  	});
				  	return
				  }
                  chores();
                })
                .catch(error => {
                  message(error.response.data.msg ?? "操作失败,请联系管理员", {
                    type: "error"
                  });
                });
            }
          }
        });
      }
    });
  }
  onMounted(async () => {
    onSearch();
	getMaterialData();
  });

  function handleDelete(row) {
    delDeliveryOrderApi({ deliveryOrderId: row.deliveryOrderId }).then((res) => {
	  if(res.code !== 200) {
	  	message(res.msg ?? "操作失败,请联系管理员", {
	  	  type: "error"
	  	});
	  	return
	  }
      message(`删除成功`, { type: "success" });
      onSearch();
    });
  }
  function onDetail(row) {
	getDeliveryOrderShowApi({ deliveryOrderId: row.deliveryOrderId }).then(res => {
		if(res?.code === 200) {
			for (let item of materialOptions.value) {
				for (let row of res.result.orderProducts) {
					
					if(item.materialId === row.materialId) {
						row.materialCode = item.code
						row.materialName = item.name
						row.categoryName = item.category.name
						row.unitName = item.unit.name
						row.actualityNum = 0
						
					}
				}
			}
			res.result.orderTypeName = getOrderType(res.result.orderType)
			addDialog({
				top: "5vh",
				width: "70%",
				title: "出库单详情",
				hideFooter: true,
				contentRenderer: () => h(Details),
				props: {
					info: res.result
				}
			});
		}
		
	});
  }
  function handleCancel(row) {
  	  
  }
  return {
    form,
    isShow,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    resetForm,
    openDialog,
    handleSizeChange,
    handleCurrentChange,
    deviceDetection,
    handleDelete,
	onDetail,
	handleCancel
  };
}
